// pages/commodityMgt/index.js
import Common from '../../common/common.js';
let common = new Common;
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //0全部商品页 1未上架商品页 2 已上架商品页
    currentTab: 0,
    //是否显示上下架按钮和复选框
    manageOpe: false,
    //全部商品/上架商品/未上架数量
    goodsCount: {},
    //商品分类列表
    goodTypeList: [],
    //查询用-商品名称或国际条码
    keyValue: "",
    //查询用-商品分类ID
    goodsTypeId: "",
    //查询用-上架状态
    shelfStatus: null,
    //商品列表
    listArray: [
      [], [], [], [], []
    ],
    //上拉加载控制
    isLoadingArray: [false, false, false, false, false],
    isFirstLoadingArray: [true, true, true, true, true],
    hasDataArray: [true, true, true, true, true],
    pageNumArray: [1, 1, 1, 1, 1],
    pageSizeArray: [10, 10, 10, 10, 10],
    //是否iphone x
    ipx:'',
    //上下架提示窗
    showModal: false,
    //控制弹窗内容 up上架down下架
    upOrDown: 'up',
    //控制底部按钮显隐 up显示上架按钮 down显示下架按钮 up_down显示上架+下架按钮
    upOrDownBtn: 'up_down',
  },
  /**
   * 选择商品
   */
  checkboxChange: function (e) {
    var goodsId = e.currentTarget.dataset.goodsid;
    var valueArray = e.detail.value;
    var checked = false;
    if (valueArray[0] == goodsId){
      //每个商品一个checkboxgroup，如果data-goodsid值和checkbox返回的值相等，表示选中商品
      checked = true;
    }
    var currentTab = this.data.currentTab;
    var listArray = this.data.listArray;
    for (var i = 0; i < listArray[currentTab].length; i++) {
      // if (listArray[currentTab][i].goodsId == goodsId) {
      if (listArray[currentTab][i].goodsId == goodsId) {  
        listArray[currentTab][i].checked = checked;
        break;
      }
    }
    this.setData({
      listArray : listArray
    })
    //控制底部按钮的显隐
    this.setBottomBth();
  },
  /**
   * 全选
   */
  checkboxChangeAll: function (e) {
    var valueArray = e.detail.value;
    var checked = false;
    if (valueArray[0] == 'all') {
      //全选
      checked = true;
    }
    var currentTab = this.data.currentTab;
    var listArray = this.data.listArray;
    for (var i = 0; i < listArray[currentTab].length; i++) {
      if (listArray[currentTab][i].shelfStatus != 1){
        listArray[currentTab][i].checked = checked;
      }
    }
    this.setData({
      listArray: listArray
    })
    //控制底部按钮的显隐
    this.setBottomBth();
  },
  /**
   * 控制底部按钮的显隐
   */
  setBottomBth: function (e) {
    var data = this.getChoosedGoods();
    if (data.length == 0) {
      return;
    }
    var upArray = [];
    var downArray = [];
    for (var i = 0; i < data.length; i++) {
      if (data[i].shelfStatus == '3') {
        downArray.push(data[i]);
      } else {
        upArray.push(data[i]);
      }
    }
    //控制底部按钮的显隐
    var upOrDownBtn = '';
    if (upArray.length > 0 && downArray.length > 0) {
      upOrDownBtn = 'up_down';
    } else {
      if (upArray.length == 0) {
        upOrDownBtn = 'down';
      } else if (downArray.lenth == 0) {
        upOrDownBtn = 'up';
      } else {
        upOrDownBtn = 'up';
      }
    }
    this.setData({
      upOrDownBtn: upOrDownBtn
    })
  },
  // 点击上下架管理按钮
  upDownManage:function(){
    var that = this;
    //显示上下架按钮和复选框
    that.setData({
      manageOpe: true
    })
    // //如果当前页在全部商品页，需要跳转到未上架商品页
    // var currentTab = that.data.currentTab;
    // if (currentTab == 0){
    //   that.switchTab(1);
    // }
  },
  /**
   * 取消复选框
   */
  cancleManage: function () {
    this.setData({
      manageOpe: false
    })
  },
  /**
   * 搜索控制
   */
  inputTyping: function (e) {
    this.setData({
      keyValue: e.detail.value
    });
    this.resetAllDatas();
    this.getGoodsList();
  },
  /**
   * 扫条码
   */
  scanCode: function (e) {
    var that = this;
    wx.scanCode({
      success: (res) => {
        var result = res.result;
        that.setData({
          keyValue: result
        })
        that.resetAllDatas();
        that.getGoodsList();
      }
    })
  },
  /**
   * 切换全部商品/未上架商品/已上架商品tab页
   */
  switchNav: function (e) {
    var currentTab = e.currentTarget.dataset.current;
    if(currentTab == 0 && this.data.manageOpe){
      this.setData({
        manageOpe: false
      })
    }
    //只要切换 就重置产品分类为全部商品
    this.setData({
      goodsTypeId: "",
    })
    this.switchTab(currentTab);
  },
  /**
   * 切换全部商品/未上架商品/已上架商品tab页
   */
  switchTab: function (currentTab) {
    var that = this;
    // if (that.data.currentTab === currentTab) {
    //   return false;
    // }
    var shelfStatus = null;
    if (currentTab == 1) {
      shelfStatus = 2;
    } else if (currentTab == 2) {
      shelfStatus = 3;
    }
    that.setData({
      currentTab: currentTab,
      shelfStatus: shelfStatus,
      manageOpe: false
    })
    //加载该标签页数据
    that.getGoodsTypeList();
    var isFirstLoadingArray = that.data.isFirstLoadingArray;
    if (isFirstLoadingArray[currentTab]) {
      that.getGoodsList();
      //设置非第一次加载
      isFirstLoadingArray[currentTab] = false;
      that.setData({
        isFirstLoadingArray: isFirstLoadingArray
      })
    }
  },
  /**
   * 切换商品分类
   */
  switchGoodsType: function (e) {
    var that = this;
    var goodsTypeId = e.currentTarget.dataset.id;
    if (that.data.goodsTypeId === goodsTypeId) {
      return false;
    }
    that.setData({
      goodsTypeId: goodsTypeId
    })
    that.resetAllDatas();
    that.getGoodsList();
  },
  /**
   *  查询全部商品、上架、下架商品数量
   */
  queryGoodsThreeTotal: function () {
    var that = this;
    var data = {
      "orgSeq": getApp().globalData.orgSeq
    };
    common.requestAjax('/api/goods-service/v1/goods/queryGoodsThreeTotal', 'POST', data).then(res => {
      if (res.data.code == 1) {
        that.setData({
          goodsCount: res.data.result
        })
      }
    }).catch(err => {
      common.showToast("系统异常，请稍后重试！");
    })
  },
  /**
   *  获取商品分类列表
   */
  getGoodsTypeList: function(){
    var that = this;
    var data = {
      "orgSeq": getApp().globalData.orgSeq,
      "shelfStatus": that.data.shelfStatus
    };
    common.requestAjax('/api/goods-service/v1/goods/getTypeNumList', 'POST', data).then(res => {
      if (res.data.code == 1) {
        this.setData({
          goodTypeList: res.data.records
        })
      } else {
        common.showToast(res.data.message);
      }
    }).catch(err => {
      common.showToast(err);
    })
  },
  /**
   *  获取商品列表
   */
  getGoodsList: function () {
    var that = this;
    var currentTab = that.data.currentTab;
    var data = {
      "size": that.data.pageSizeArray[currentTab],
      "current": that.data.pageNumArray[currentTab],
      "condition": {
        "orgSeq": getApp().globalData.orgSeq,
        "goodsName": that.data.keyValue,
        "goodsTypeId": that.data.goodsTypeId,
        "shelfStatus": that.data.shelfStatus
      }
    };
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    common.requestAjax('/api/goods-service/v1/goods/queryStoreGoodsList', 'POST', data).then(res => {
      wx.hideLoading();
      if (res.data.code == 1) {
        var list = res.data.records;
        var listArray = that.data.listArray;
        for (var i = 0; i < list.length; i++) {
          listArray[currentTab].push(list[i]);
        }
        //是否显示暂无数据
        var hasDataArray = that.data.hasDataArray;
        if (list.length == 0) {
          //每个标签页的第一页
          if (that.data.pageNumArray[currentTab] == 1) {
            hasDataArray[currentTab] = false;
          } else {
            hasDataArray[currentTab] = true;
          }
        } else {
          hasDataArray[currentTab] = true;
        }
        //调整数据
        that.setData({
          listArray: listArray,
          hasDataArray: hasDataArray
        })
      }
      //上拉加载控制
      if (res.data.records == null || res.data.records.length == 0) {
        that.errorDatasArray();
      } else {
        that.successDatasArray();
      }
    }).catch(err => {
      wx.hideLoading();
      that.errorDatasArray();
      common.showToast("1系统异常，请稍后重试！");
    })
  },
  /**
   * 弹窗提示是否上下架
   */
  showModel: function (e){
    var flag = e.currentTarget.dataset.flag;
    //已选择的商品列表
    var data = this.getChoosedGoods(flag);
    if (data.length == 0) {
      common.showToast("请选择商品");
      return;
    }
    this.setData({
      showModal: true,
      upOrDown: flag,
      choosedGoodsNum: data.length
    })
  },
  /**
   * 已选择的商品列表
   */
  getChoosedGoods: function (flag) {
    var that = this;
    var data = [];
    var listArray = that.data.listArray;
    var list = listArray[that.data.currentTab];
    for (var j = 0; j < list.length; j++) {
      if (list[j].checked) {
        if (flag == 'up') {
          //全部上架，只要当前状态为下架的数据
          if (list[j].shelfStatus == 2) {
            data.push({
              "goodsId": list[j].goodsId,
              "orgSeq": getApp().globalData.orgSeq,
              "shelfStatus": list[j].shelfStatus
            })
          }
        } else if (flag == 'down') {
          //全部下架，只要当前状态为上架的数据
          if (list[j].shelfStatus == 3) {
            data.push({
              "goodsId": list[j].goodsId,
              "orgSeq": getApp().globalData.orgSeq,
              "shelfStatus": list[j].shelfStatus
            })
          }
        } else {
          //获取勾选的原始数据
          data.push({
            "goodsId": list[j].goodsId,
            "orgSeq": getApp().globalData.orgSeq,
            "shelfStatus": list[j].shelfStatus
          })
        }
      }
    }
    return data;
  },
  /**
   * 取消弹窗
   */
  cancleModel: function () {
    this.setData({
      showModal: false
    })
  },
  /**
   *  提交上下架
   */
  batchUpLowerManage: function (e) {
    var that = this;
    var flag = e.currentTarget.dataset.flag;
    //已选择的商品列表
    var data = that.getChoosedGoods(flag);
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    //修改已选中商品的状态供修改接口使用
    var dataFix = [];
    for(var i=0; i<data.length; i++){
      if (data[i].shelfStatus == 3){
        data[i].shelfStatus = 2;
        dataFix.push(data[i]);
      } else {
        data[i].shelfStatus = 3;
        dataFix.push(data[i]);
      }
    }
    common.requestAjax('/api/goods-service/v1/goods/batchUpLowerManage', 'POST', dataFix).then(res => {
      wx.hideLoading();
      if (res.data.code == 1) {
        common.showToast(res.data.message);
        that.cancleModel();
        that.cancleManage();
        that.resetAllDatas();
        that.getGoodsList();
        that.queryGoodsThreeTotal();
      } else {
        common.showToast(res.data.message);
      }
    }).catch(err => {
      wx.hideLoading();
      common.showToast("系统异常，请稍后重试！");
    })
  },
  /**
   * 上拉加载重置所有数据
   */
  resetAllDatas: function () {
    var that = this;
    that.setData({
      pageNumArray: [1, 1, 1, 1, 1],
      listArray: [
        [],
        [],
        [],
        [],
        []
      ],
      isFirstLoadingArray: [true, true, true, true, true]
    })
  },
  /**
   * 上拉加载成功处理
   */
  successDatasArray: function () {
    var that = this;
    var currentTab = that.data.currentTab;
    var pageNumArray = that.data.pageNumArray;
    //当前标签页是否为首次加载设为false
    if (pageNumArray[currentTab] == 1) {
      var isFirstLoadingArray = that.data.isFirstLoadingArray;
      that.setData({
        ["isFirstLoadingArray[" + currentTab + "]"]: false
      })
    }
    //标识设置加载完成，页数+1
    that.setData({
      ["isLoadingArray[" + currentTab + "]"]: false,
      ["pageNumArray[" + currentTab + "]"]: pageNumArray[currentTab] + 1
    })
    //隐藏导航栏loading
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
  /**
   * 上拉加载失败处理
   */
  errorDatasArray: function () {
    var that = this;
    var currentTab = that.data.currentTab;
    var isLoadingArray = that.data.isLoadingArray;
    //标识设置加载完成
    this.setData({
      ["isLoadingArray[" + currentTab + "]"]: false
    })
    //隐藏导航栏loading
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
  /**
   * 上拉加载事件
   */
  scrollTolower(e) {
    var that = this;
    var currentTab = that.data.currentTab;
    var isLoadingArray = that.data.isLoadingArray;
    //正在加载中阻止再次查询
    if (isLoadingArray[currentTab]) {
      return;
    }
    //显示导航栏loading
    wx.showNavigationBarLoading();
    //设置标识加载中
    that.setData({
      ["isLoadingArray[" + currentTab + "]"]: true
    })
    //获取数据
    that.getGoodsList();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let ipx = app.globalData.isIphoneX;
    this.setData({
      ipx: ipx
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    // getApp().globalData.orgSeq = "20529a0a-3f9b-41ab-9a29-91390ae8b84b";
    /**
     *  获取商品分类列表
     */
    this.getGoodsTypeList();
    /**
     *  获取商品列表
     */
    this.getGoodsList();
    /**
     *  查询全部商品、上架、下架商品数量
     */
    this.queryGoodsThreeTotal();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var that = this;
    var currentTab = that.data.currentTab;
    var isLoadingArray = that.data.isLoadingArray;
    //正在加载中阻止再次查询
    if (isLoadingArray[currentTab]) {
      return;
    }
    //显示导航栏loading
    wx.showNavigationBarLoading();
    //设置标识加载中
    isLoadingArray[currentTab] = true;
    that.setData({
      isLoadingArray: isLoadingArray
    })
    //获取数据
    that.resetAllDatas();
    that.getGoodsList();
    that.getGoodsTypeList();
    that.queryGoodsThreeTotal();
    setTimeout(function () {
      wx.stopPullDownRefresh();
    }, 10)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})